package com.xiaoyun.controller;

import com.xiaoyun.constant.Const;
import com.xiaoyun.pojo.Users;
import com.xiaoyun.service.UserService;
import com.xiaoyun.utils.JsonUtils;
import com.xiaoyun.utils.MD5Utils;
import com.xiaoyun.utils.RedisUtil;
import com.xiaoyun.utils.XYJSONResult;
import com.xiaoyun.vo.UsersVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequiredArgsConstructor
public class SSOController {

    private final UserService userService;

    private final RedisUtil redisUtil;

    @GetMapping("/login")
    public String login(String returnUrl, Model model, HttpServletRequest request,
                        HttpServletResponse response) {
        model.addAttribute("returnUrl", returnUrl);
        String userTicket = getCookie(request, Const.COOKIE_USER_TICKET);
        boolean isVerified = verifyUserTicket(userTicket);
        if (isVerified) {
            String tmpTicket = createTmpTicket();
            return "redirect:" + returnUrl + "?tmpTicket=" + tmpTicket;
        }
        return "login";
    }

    private boolean verifyUserTicket(String userTicket) {
        if (StringUtils.isBlank(userTicket)) {
            return false;
        }
        String userRedis = redisUtil.getKey(Const.REDIS_USER_TICKET + ":" + userTicket);
        if (StringUtils.isBlank(userRedis)) {
            return false;
        }
        return true;
    }

    @PostMapping("/doLogin")
    public String doLogin(
            @NotBlank String username,
            @NotBlank String password,
            String returnUrl,
            Model model, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        Users userResult = userService.queryUserForLogin(username, MD5Utils.getMD5Str(password)).get();
        if (userResult == null) {
            model.addAttribute("errmsg", "用户名密码不正确");
            return "login";
        }

        //生成用户token
        String uniqueToken = UUID.randomUUID().toString().trim();
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(userResult, usersVO);
        usersVO.setUserUniqueToken(uniqueToken);

        redisUtil.setKey(Const.REDIS_USER_TOKEN + ":" + userResult.getId(), JsonUtils.objectToJson(usersVO));

        String userTicket = UUID.randomUUID().toString().trim();

        setCookie(Const.COOKIE_USER_TICKET, userTicket, response);

        redisUtil.setKey(Const.REDIS_USER_TICKET + ":" + userTicket, userResult.getId());

        String tmpTicket = createTmpTicket();

        return "redirect:" + returnUrl + "?tmpTicket=" + tmpTicket;
//        return "login";
    }

    private String createTmpTicket() {
        String temTicket = UUID.randomUUID().toString().trim();
        try {
            redisUtil.setKey(Const.REDIS_TMP_TICKET + ":" + temTicket,
                    MD5Utils.getMD5Str(temTicket), 600, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return temTicket;
    }

    private void setCookie(String key, String val,
                           HttpServletResponse response) {
        Cookie cookie = new Cookie(key, val);
        cookie.setDomain("sso.com");
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    private void delCookie(String key,
                           HttpServletResponse response) {
        Cookie cookie = new Cookie(key, null);
        cookie.setDomain("sso.com");
        cookie.setPath("/");
        cookie.setMaxAge(-1);
        response.addCookie(cookie);
    }

    private String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || StringUtils.isBlank(key)) {
            return null;
        }
        String cookieValue = null;
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals(key)) {
                cookieValue = cookies[i].getValue();
                break;
            }
        }
        return cookieValue;
    }


    @PostMapping("/verifyTemTicket")
    @ResponseBody
    public XYJSONResult verifyTmpTicket(String tmpTicket,
                                        HttpServletRequest request,
                                        HttpServletResponse response) throws Exception {
        String tmpTicketValue = redisUtil.getKey(Const.REDIS_TMP_TICKET + ":" + tmpTicket);
        if (StringUtils.isBlank(tmpTicketValue)) {
            return XYJSONResult.errorUserTicket("用户票据异常");
        }
        if (!tmpTicketValue.equals(MD5Utils.getMD5Str(tmpTicket))) {
            return XYJSONResult.errorUserTicket("用户票据异常");
        } else {
            redisUtil.removeKey(Const.REDIS_TMP_TICKET + ":" + tmpTicket);
        }

        String userTicket = getCookie(request, Const.COOKIE_USER_TICKET);
        String userId = redisUtil.getKey(Const.REDIS_USER_TICKET + ":" + userTicket);
        if (StringUtils.isBlank(userId)) {
            return XYJSONResult.errorUserTicket("用户票据异常");
        }
        String userRedis = redisUtil.getKey(Const.REDIS_USER_TOKEN + ":" + userId);
        if (StringUtils.isBlank(userRedis)) {
            return XYJSONResult.errorUserTicket("用户票据异常");
        }
        return XYJSONResult.ok(JsonUtils.jsonToPojo(userRedis, UsersVO.class));
    }

    @PostMapping("/logout")
    @ResponseBody
    public XYJSONResult logout(String userId,
                               HttpServletRequest request,
                               HttpServletResponse response) throws Exception {
        String userTicket = getCookie(request, Const.COOKIE_USER_TICKET);
        delCookie(Const.COOKIE_USER_TICKET, response);
        redisUtil.removeKey(Const.REDIS_USER_TICKET + ":" + userTicket);
        redisUtil.removeKey(Const.REDIS_USER_TOKEN + ":" + userId);
        return XYJSONResult.ok();
    }
}
